package com.ts.main.admin.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ts.main.admin.constants.JwtConstant;
import com.ts.main.admin.constants.RedisPrefixConstants;
import com.ts.main.admin.context.UserContext;
import com.ts.main.admin.dto.AdminDto;
import com.ts.main.admin.dto.AdminLoginDto;
import com.ts.main.admin.dto.AdminSearchPageDto;
import com.ts.main.admin.entity.AdminEntity;
import com.ts.main.admin.exception.CommonException;
import com.ts.main.admin.exception.EmError;
import com.ts.main.admin.exception.RPage;
import com.ts.main.admin.mapper.AdminMapper;
import com.ts.main.admin.po.AdminPo;
import com.ts.main.admin.utils.JwtTokenUtil;
import com.ts.main.admin.utils.RedisUtil;
import com.ts.main.admin.vo.AdminVo;
import com.ts.main.admin.vo.AdminRolePartVo;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author lk
 * @description 针对表【t_admin(用户表)】的数据库操作Service实现
 * @createDate 2025-06-09 00:38:59
 */
@AllArgsConstructor
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdminEntity> {

    private final RedisUtil redisUtil;
    private final AdminRoleServiceImpl adminRoleService;
    private final String password = "123456";

    public AdminVo login(AdminLoginDto dto) {
        if(StringUtils.isBlank(dto.getAccount())) throw new CommonException(EmError.USER_ADD_IS_NULL);
        //用户信息
        AdminPo adminPo = baseMapper.getAdminInfo(null,dto.getAccount());
        if (ObjectUtil.isEmpty(adminPo)) throw new CommonException(EmError.AUTH_USER_IS_NULL);
        // 用户是否被禁用
        if (adminPo.getIsBlocked()) throw new CommonException(EmError.AUTH_USER_IS_BLOCK_LOGIN);
        // 校验密码
        if (!dto.getPassword().equals(adminPo.getPassword())) throw new CommonException(EmError.AUTH_PASSWORD_ERROR);
        //构建返回对象
        AdminVo adminVo = new AdminVo();
        BeanUtils.copyProperties(adminPo, adminVo);
        // 生成JwtToken
        long expireTime = dto.getRememberMe() ? JwtConstant.EXPIRATION_REMEMBER : JwtConstant.EXPIRATION;
        String token = JwtTokenUtil.createToken(adminVo.getId().toString(), expireTime * 1000L);
        adminVo.setToken(token);
        // 存入Redis，如果缓存时间更长就使用缓存时间
        Long redisExpireTime = redisUtil.getExpire(RedisPrefixConstants.ADMIN_USER_INFO + adminVo.getId());
        if (Objects.nonNull(redisExpireTime) && redisExpireTime > expireTime) {
            expireTime = redisExpireTime;
        }
        redisUtil.setObject(RedisPrefixConstants.ADMIN_USER_INFO + adminVo.getId(), adminVo, expireTime);
        return adminVo;
    }

    public Boolean resetPassword(Integer id) {
        LambdaUpdateWrapper<AdminEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(AdminEntity::getId, id)
                .set(AdminEntity::getPassword, password);
        //清除Redis数据，强制重新登录改密
        redisUtil.deleteKey(RedisPrefixConstants.ADMIN_USER_INFO + id);
        return this.update(updateWrapper);
    }

    public AdminDto saveUser(AdminDto dto) {
        //判断用户名是否为空或
        if (ObjectUtils.isEmpty(dto.getAccount()) || ObjectUtils.isEmpty(dto.getUserName())) {
            throw new CommonException(EmError.USER_ADD_IS_NULL);
        }
        //判断账号是否存在
        AdminPo adminPo = baseMapper.getAdminInfo(null,dto.getAccount());
        if (!ObjectUtils.isEmpty(adminPo)) {
            throw new CommonException(EmError.USER_ADD_IS_EXIST);
        }
        dto.setPassword(password);
        dto.setIsBlocked(false);
        save(BeanUtil.copyProperties(dto, AdminEntity.class));
        return dto;
    }

    public Boolean updateUser(AdminDto dto) {
        //判断用户名是否为空或
        if (ObjectUtils.isEmpty(dto.getAccount()) || ObjectUtils.isEmpty(dto.getUserName())) {
            throw new CommonException(EmError.USER_ADD_IS_NULL);
        }
        //判断账号是否存在
        AdminPo adminPo = baseMapper.getAdminInfo(dto.getId(),dto.getAccount());
        if (!ObjectUtils.isEmpty(adminPo)) {
            throw new CommonException(EmError.USER_ADD_IS_EXIST);
        }
        return this.updateById(BeanUtil.copyProperties(dto, AdminEntity.class));
    }

    public Object deleteUser(Integer id) {
        AdminVo user = UserContext.getUser();
        if(!user.getId().equals(1)) throw new CommonException(EmError.AUTH_API_NOT_PERMISSION);
        LambdaUpdateWrapper<AdminEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(AdminEntity::getId, id)
                .set(AdminEntity::getIsDeleted, true);
        return this.update(updateWrapper);
    }

    public RPage<List<AdminVo>> getUserList(AdminSearchPageDto dto) {
        Page<Object> page = PageHelper.startPage(dto.getPage(), dto.getLimit());
        List<AdminVo> list = baseMapper.getUserList(dto);
        return RPage.ok(list, dto.getPage(),dto.getLimit(), page.getTotal());
    }

    public AdminVo getUserDetails(Integer id) {
        return baseMapper.getUserDetails(id);
    }

    public List<AdminRolePartVo> getRoleList() {
        return adminRoleService.getRoleList();
    }


}




